function getRootPath() {
    return $('#rootPath').val();
}

function selectedPath(eleId, value) {
    var rootPath = $('#rootPath').val();
    if(/^temp_out_/.test(eleId)){
        if(!rootPath){
            layui.layer.msg('请先选择项目根路径');
            return;
        }
        rootPath = rootPath.replaceAll('\\','\\\\');
        if(!new RegExp('^' + rootPath).test(value)){
            layui.layer.open({
                title: '错误',
                content: '输出路径必须以项目根路径开头'
            });
            return;
        }
    }
    if(eleId === 'rootPath'){
        $('.path-select').each(function (idx, ele) {
            if($(ele).val()){
                var temp = $(ele).val().replace(rootPath, '');
                if(temp !== ''){
                    if(/^\\/.test(temp)){
                        if(/\\$/.test(value)){
                            $(ele).val(value + temp.slice(1))
                        }else {
                            $(ele).val(value + temp)
                        }
                    }else {
                        if(/\\$/.test(value)){
                            $(ele).val(value + temp)
                        }else {
                            $(ele).val(value + '\\' + temp)
                        }
                    }
                }else {
                    $(ele).val(value)
                }
            }
        })
    }
    $('#' + eleId).val(value);
}

function reloadTable() {
    $(".layuimini-tab .layui-tab-title li", parent.document).each(function (idx, item) {
        if($(item).attr('lay-id').indexOf('project/list.html') !== -1){
            $(".layuimini-tab .layui-tab-content .layui-tab-item", parent.document).each(function (i, e){
                if(idx === i){
                    $(e).find('iframe')[0].contentWindow.reload();
                }
            })
        }
    });
}

layui.use(['form', 'table' , 'element'], function () {
    var $ = layui.jquery,
        element = layui.element,
        form = layui.form;

    //初始化数据库下拉
    $.ajax({
        type: "GET",
        url: "/database/option",
        data: {page:1,limit:100},
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function(result) {
            if(result.code === 0 && result.data && result.data.length > 0){
                var options = "";
                for (const item of result.data) {
                    options += "<option value='"+ item.id +"'>"+item.dbName+"（"+item.host+":"+item.port+"）"+"</option>";
                }
                $("#dbSelect").append(options)
                //$($('#dbSelect').find('option')).after(options);
                form.render();
            } else {
                layer.msg(result.msg, {
                    icon: 5
                });
            }
        }
    });

    //保存项目模板
    form.on('submit(saveProject)', function (data) {
        var tempInfo = []
        $('.code-template').each(function (idx, ele) {
            var tempId = $($(ele).find('input')[0]).attr('temp-id');
            var templateName = $($(ele).find('input')[0]).val();
            var packageName = $($(ele).find('input')[1]).val();
            var outputPath = $($(ele).find('input')[2]).val();
            if(data.field.id){
                tempInfo.push({projectId: data.field.id, templateId: tempId, templateName: templateName, packageName: packageName, outputPath: outputPath});
            }else {
                tempInfo.push({templateId: tempId, templateName: templateName, packageName: packageName, outputPath: outputPath});
            }
        })
        data.field.templates = tempInfo;
        $.ajax({
            type: "POST",
            url: "/project/save",
            data: JSON.stringify(data.field),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function(result) {
                if(result && result.code === 0){
                    var index = layer.alert(result.msg, { title: '提示', closeBtn: 0 }, function () {
                        layer.close(index);
                        reloadTable();
                        deleteCurrentByIframe();
                    });
                }else if(result && result.msg){
                    layer.alert(result.msg, { title: '提示' });
                }else {
                    layer.alert("保存失败", { title: '提示' });
                }
            }
        });
        /*postAjax("/project/save", data.field, function (result) {
            if(result && result.code === 0){
                var index = layer.alert(result.msg, { title: '提示', closeBtn: 0 }, function () {
                    layer.close(index);
                    reloadTable();
                    deleteCurrentByIframe();
                });
            }else if(result && result.msg){
                layer.alert(result.msg, { title: '提示' });
            }else {
                layer.alert("保存失败", { title: '提示' });
            }
        });*/
        return false;
    });

    //初始化数据库下拉
/*    getAjax(basePath + "/database/option", {page:1,limit:100}, function (result) {
        if(result.code === 0 && result.data && result.data.length > 0){
            var options = "";
            for (const item of result.data) {
                options += "<option value='"+ item.id +"'>"+item.dbName+"（"+item.host+":"+item.port+"）"+"</option>";
            }
            $($('#dbSelect').find('option')).after(options);
            form.render('select', 'editForm');
        }
    }, true);*/

    //选择路径
    $("body").on('click', '.select-path', function () {
        var eleId = $(this).parents('.layui-form-item').find('input').attr('id');
        if(!eleId){
            eleId = $(this).parents('.layui-inline').find('input').attr('id');
            if(!$('#rootPath').val()){
                layer.msg("请先选择项目根路径");
                return;
            }
        }
        var index = layer.open({
            title: '选择路径',
            type: 2,
            shade: 0.2,
            area: ['500px', '350px'],
            content:'/api/file/toPath-Selector',
            success: function (layero, index) {
                //窗口初始化
                window['layui-layer-iframe' + index].initParent(eleId, $('#rootPath').val());
            }
        });
    });
    function deleteCurrentByIframe() {
        var ele = $(".layuimini-tab .layui-tab-title li.layui-this", parent.document);
        if (ele.length > 0) {
            var layId = $(ele[0]).attr('lay-id');
            del(layId, true);
        }
    }
    function del(tabId, isParent) {
        // todo 未知BUG，不知道是不是layui问题，必须先删除元素
        $(".layuimini-tab .layui-tab-title .layui-unselect.layui-tab-bar").remove();

        if (isParent === true) {
            parent.layui.element.tabDelete('layuiminiTab', tabId);
        } else {
            element.tabDelete('layuiminiTab', tabId);
        }
    }

});

